#include <dbg.h>

#include <cassert>

using namespace std;

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int res = 0;
        int left = 0;
        unordered_map<int, int> cnt;
        for (int right = 0; right < fruits.size(); ++right) {
            ++cnt[fruits[right]];  // 统计当前窗口内每种水果的数量
            while (cnt.size() >
                   2) {  // 如果当前窗口内的水果种类大于2，就需要缩小窗口
                auto it = cnt.find(fruits[left]);  // 找到最左边的水果
                --it->second;
                if (it->second == 0) {
                    cnt.erase(it);
                }
                ++left;
            }
            res = max(res, right - left + 1);
        }
        return res;
    }
};

int main() {
    Solution s;

    vector<int> fruits = {1, 2, 1};
    vector<int> fruits2 = {0, 1, 2, 2};
    vector<int> fruits3 = {1, 2, 3, 2, 2};
    vector<int> fruits4 = {3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4};

    assert(s.totalFruit(fruits) == 3);
    assert(s.totalFruit(fruits2) == 3);
    assert(s.totalFruit(fruits3) == 4);
    assert(s.totalFruit(fruits4) == 5);

    return 0;
}